﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OAuth;
using System.Collections.Specialized;
using System.Xml;
using Darren.Common.Helper;

namespace OAuth
{
    /// <summary>
    ///SinaOAuth 的摘要说明
    /// </summary>
    public class SinaOAuth : OAuthBase
    {
        public static string AppKey
        {
            get { return ConfigHelper.GetConfigString("Sina_AppKey"); }
        }
        public static string AppSecret
        {
            get { return ConfigHelper.GetConfigString("Sina_AppSecret"); }
        }
        public static string CallBackURL
        {
            get { return ConfigHelper.GetConfigString("Sina_CallBackURL"); }
        }
        public SinaOAuth()
        {
            this.app_id = SinaOAuth.AppKey;
            this.app_key = SinaOAuth.AppSecret;
        }
        private string oauth_callback;
        public string Oauth_callback { get { return oauth_callback; } set { oauth_callback = value; } }

        private const string AccessToken_url = "http://api.t.sina.com.cn/oauth/access_token";
        private const string AUTHORIZE = "http://api.t.sina.com.cn/oauth/authorize";
        private const string RequestToken = "http://api.t.sina.com.cn/oauth/request_token";
        private const string get_user_info_url = "http://api.t.sina.com.cn/users/show.xml";


        public SinaOAuth(string _appid, string _appkey)
            : base(_appid, _appkey)
        {
           
        }

        //获取登录地址
        public string Login(out AccessToken token, string callbackUrl)
        {
            if (string.IsNullOrEmpty(callbackUrl))
                throw new ArgumentNullException("请提供Oauth_callback属性");


            string result = GenResponse(RequestToken); 
            NameValueCollection nvc = HttpUtility.ParseQueryString(result);
            if (nvc["error_code"] != null)
            {
                throw new Exception("error");
            }
            token = new AccessToken();
            token.Token = nvc["oauth_token"];
            token.TokenSecret = nvc["oauth_token_secret"];
            return string.Format("{0}?oauth_consumer_key={3}&oauth_token={1}&oauth_callback={2}", AUTHORIZE, token.Token, callbackUrl, this.app_id);
        }
        public string UpdateStatus(string content)
        {
            checkToken();
            content = Microsoft.JScript.GlobalObject.encodeURIComponent(content);
            //一定要用POST方法
            string url = string.Format("http://api.t.sina.com.cn/statuses/update.xml?status={0}&source={1}", content, this.app_id);
            //为了支持中文，一定要通过 Microsoft.JScript.GlobalObject.encodeURIComponent编码，不能用HttpUtility.UrlEncode        

            
            return GenResponse(url,"POST");
            
        }


        /// <summary>
        /// 返回登录用户最近收藏的20条微博消息
        /// </summary>
        /// <returns></returns>
        public string GetFavorites(int page)
        {
            checkToken();
            string url = "http://api.t.sina.com.cn/favorites.xml?page="+page.ToString();
            return GenResponse(url);
        }
        /// <summary>
        /// 返回当前用户可能感兴趣的用户
        /// </summary>
        /// <returns></returns>
        public string GetInterestedUsers()
        {
            checkToken();
            string url = "http://api.t.sina.com.cn/users/suggestions.xml";
            return GenResponse(url);
        }

        /// <summary>
        /// 返回最近一周内的热门话题。 
        /// </summary>
        /// <returns></returns>
        public string GetWeeklyHotTopic()
        {
            checkToken();
            string url = "http://api.t.sina.com.cn/trends/weekly.xml";
            return GenResponse(url);
        }

        //获取粉丝资料
        public string GetFriendInfo()
        {
            checkToken();
            string url = "http://api.t.sina.com.cn/statuses/friends_timeline.xml";
            return GenResponse(url);
        }
        //获取用户的关注列表
        public string GetFriends()
        {
            checkToken();
            string url = "http://api.t.sina.com.cn/friends/ids.json";
            return GenResponse(url);
        }
        public string GetFriends(string uid)
        {
            if (string.IsNullOrEmpty(uid))
            {
                return GetFriends();
            }
            checkToken();
            string url = "http://api.t.sina.com.cn/friends/ids.json?user_id="+uid;
            return GenResponse(url);
        }
        //关注一个用户。关注成功则返回关注人的资料，目前的最多关注2000人。
        public string FriendshipsCreate(string uid)
        {
            checkToken();
            string url = "http://api.t.sina.com.cn/friendships/create.xml?user_id=" + uid;
            return GenResponse(url,"POST");
        }

        //获得表情
        public string GetFaces()
        {
            checkToken();
            string url = "http://api.t.sina.com.cn/emotions.xml";
            return GenResponse(url);
        }
        
        //获取用户基本资料
        public MemberInfo GetUserInfo()
        {
            checkToken();
            if (this.Token.Openid == null)
                throw new Exception("this.Token.Openid不能为空");
            string url = string.Format("{1}?user_id={0}", this.Token.Openid, get_user_info_url);
            string result= GenResponse(url);

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(result);
            string displayName = doc.SelectSingleNode("/user/name").InnerXml;
            string imageurl = doc.SelectSingleNode("/user/profile_image_url").InnerXml;
            string memberid = doc.SelectSingleNode("/user/id").InnerXml;
            return new MemberInfo(displayName, memberid, imageurl);
        }
        /// <summary>
        /// 获取授权参数，如openid
        /// </summary>
        /// <param name="oauth_token">未授权的token</param>
        /// <param name="oauth_vericode">授权验证码，请使用上一步返回的oauth_vericode </param>
        /// <param name="oauth_token_secret">上一步返回的密钥token_secret</param>
        /// <returns></returns>
        public AccessToken GetAccessToken(string oauth_vericode)
        {

            string url = string.Format("{0}?oauth_verifier={1}", AccessToken_url, oauth_vericode);
            string result = GenResponse(url);
            NameValueCollection nvc = HttpUtility.ParseQueryString(result);
            if (nvc["error_code"] != null)
            {
                throw new Exception("error");
            }
            return new AccessToken(nvc["oauth_token"], nvc["oauth_token_secret"], nvc["user_id"]);
        }
    }
}